#include "inc.h"

#if LUA_VERSION_NUM < 502
    LUALIB_API void luaL_requiref (lua_State *L, const char *modname, lua_CFunction openf, int glb) {
        lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
        lua_getfield(L, -1, modname);  /* LOADED[modname] */
        if (!lua_toboolean(L, -1)) {  /* package not already loaded? */
            lua_pop(L, 1);  /* remove field */
            lua_pushcfunction(L, openf);
            lua_pushstring(L, modname);  /* argument to open function */
            lua_call(L, 1, 1);  /* call 'openf' to open module */
            lua_pushvalue(L, -1);  /* make copy of module (call result) */
            lua_setfield(L, -3, modname);  /* LOADED[modname] = module */
        }
        lua_remove(L, -2);  /* remove LOADED table */
        if (glb) {
            lua_pushvalue(L, -1);  /* copy of module */
            lua_setglobal(L, modname);  /* _G[modname] = module */
        }
    }
#endif


int l_aoi_create(lua_State* L);
int l_aoi_release(lua_State* L);

int l_set_cwd(lua_State* L);
int l_get_cwd(lua_State* L);

// int call_luafunc(lua_State* L);

static void init_lib(lua_State* L, const char* name, const struct luaL_Reg funcs[]) {
	lua_newtable(L);
	luaL_setfuncs(L, funcs, 0);
	lua_pushvalue(L, -1);
    lua_setglobal(L, name);
}

// 这里注意：C++的导出必须加 extern "C"
// 原因：C++的导出符号规则和C的不一样，lua是基于C的规则进行so加载的
void luaopen_libdemo(lua_State* L) {
    static const luaL_Reg funcs[] = {
		{"aoi_create",  l_aoi_create},
		{"aoi_release", l_aoi_release},
        {"set_cwd",     l_set_cwd},
        {"get_cwd",     l_get_cwd},
        // {"call_luafunc", call_luafunc},
        {NULL, NULL},
	};
    init_lib(L, "libdemo", funcs);
}